package com.designoutput.manager
{
	
	import com.designoutput.ui.newControls.ControlBase;
	import com.designoutput.ui.newControls.Modal;
	import com.designoutput.utils.Globals;
	
	import flash.display.DisplayObject;
	import flash.display.InteractiveObject;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.utils.Dictionary;

	public class PopUpManager extends ControlBase
	{
		private var _optionsDictionary:Dictionary = new Dictionary();
		public var modal:Modal;
		
		override protected function initialize():void {
			modal = new Modal();
		}
		
		public function addPopup(popup:DisplayObject, modal:Boolean = false, transparentModal:Boolean = false):void {
			_optionsDictionary[popup] = { modal: modal, transparentModal: transparentModal };
			addChild(popup);
			updateModal();
		}
		
		public function removePopup(popup:DisplayObject):void {
			removeChild(popup);
			delete _optionsDictionary[popup];
			updateModal();
		}
		
		public function bringToTop(popup:DisplayObject):void {
			setChildIndex(popup, numChildren - 1);
		}
		
		public function center(popup:DisplayObject):void {
			popup.x = int(_width/2 - popup.width/2);
			popup.y = int(_height/2 - popup.height/2);
		}
		
		public function updateModal():void {
			if(contains(modal))
				removeChild(modal);
			
			Globals.focusManager.setFocus(null);
			
			if(numChildren > 0){
				var topPopup:DisplayObject = getChildAt(numChildren - 1);
				if(_optionsDictionary[topPopup].modal){
					addChildAt(modal, numChildren - 1);
					modal.alpha = _optionsDictionary[topPopup].transparentModal ? 0 : 0.3;
				}
				
				if(topPopup is InteractiveObject)
					Globals.focusManager.setFocus(topPopup as InteractiveObject);
			}
		}
		
		override protected function updateDisplay():void {
			super.updateDisplay();
			
			modal.width = _width;
			modal.height = _height;
		}
		
		public function convertPosition(reference:Sprite, positionOnReference:Point):Point {
			positionOnReference = reference.localToGlobal(positionOnReference);
			positionOnReference = globalToLocal(positionOnReference);
			return positionOnReference;
		}
	}
}